package com.example.webcrawler.service.mpl;

import com.example.webcrawler.model.ApiRequest;
import com.example.webcrawler.service.RequestService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RequestServiceImpl implements RequestService {

    private static final Logger logger = LoggerFactory.getLogger(RequestServiceImpl.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 创建一个可重用的HTTP客户端
    private final HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    @Autowired
    private DataStorageService dataStorageService;

    @Override
    public ApiRequest sendRequest(ApiRequest request) throws Exception {
        // 发送请求并获取结果
        return sendRequestInternal(request);
    }

    @Override
    public ApiRequest saveRequest(ApiRequest request) {
        return dataStorageService.saveRequest(request);
    }

    @Override
    public List<ApiRequest> getAllSavedRequests() {
        return dataStorageService.getAllRequests();
    }

    @Override
    public ApiRequest getRequestById(String requestId) {
        return dataStorageService.getAllRequests()
                .stream()
                .filter(request -> requestId.equals(request.getRequestId()))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("未找到请求ID: " + requestId));
    }

    @Override
    public ApiRequest updateRequest(String requestId, ApiRequest request) {
        boolean success = dataStorageService.updateRequest(requestId, request);
        if (!success) {
            throw new RuntimeException("未找到请求ID: " + requestId);
        }
        return request;
    }

    @Override
    public void deleteRequest(String requestId) {
        boolean success = dataStorageService.deleteRequest(requestId);
        if (!success) {
            throw new RuntimeException("未找到请求ID: " + requestId);
        }
    }

    /**
     * 内部方法：发送请求并返回响应
     */
    private ApiRequest sendRequestInternal(ApiRequest request) throws IOException, InterruptedException {
        long startTime = System.currentTimeMillis();

        ApiRequest result = new ApiRequest();
        result.setMethod(request.getMethod());
        result.setUrl(request.getUrl());

        // 构建请求
        String method = request.getMethod() != null ? request.getMethod().toUpperCase() : "GET";
        URI uri = URI.create(request.getUrl());
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(uri)
                .timeout(Duration.ofSeconds(30));

        // 设置请求方法和请求体
        switch (method) {
            case "GET":
                requestBuilder = requestBuilder.GET();
                break;
            case "POST":
                if (request.getRequestBody() != null) {
                    requestBuilder = requestBuilder.POST(HttpRequest.BodyPublishers.ofString(request.getRequestBody()));
                } else {
                    requestBuilder = requestBuilder.POST(HttpRequest.BodyPublishers.noBody());
                }
                break;
            case "PUT":
                if (request.getRequestBody() != null) {
                    requestBuilder = requestBuilder.PUT(HttpRequest.BodyPublishers.ofString(request.getRequestBody()));
                } else {
                    requestBuilder = requestBuilder.PUT(HttpRequest.BodyPublishers.noBody());
                }
                break;
            case "DELETE":
                requestBuilder = requestBuilder.DELETE();
                break;
            default:
                requestBuilder = requestBuilder.method(method, HttpRequest.BodyPublishers.noBody());
                break;
        }

        // 添加请求头
        if (request.getRequestHeaders() != null) {
            for (Map.Entry<String, String> header : request.getRequestHeaders().entrySet()) {
                requestBuilder = requestBuilder.header(header.getKey(), header.getValue());
            }
        }

        // 发送请求
        HttpResponse<String> response = httpClient.send(requestBuilder.build(),
                HttpResponse.BodyHandlers.ofString());

        // 设置响应结果
        result.setStatus(response.statusCode());
        result.setResponseBody(response.body());
        result.setResponseTime(System.currentTimeMillis() - startTime);

        // 设置响应头
        Map<String, String> responseHeaders = new HashMap<>();
        response.headers().map().forEach((key, values) -> {
            if (values != null && !values.isEmpty()) {
                responseHeaders.put(key, values.get(0));
            }
        });
        result.setResponseHeaders(responseHeaders);

        return result;
    }
}
